/******************************************************************************
 * @file     gpio_test_startup.c
 * @version  V0.10
 * $Revision: 1 $
 * $Date: 21/02/23 9:23a $
 * @brief    IEC60730 GPIO Test
 * @note
 * SPDX-License-Identifier: Apache-2.0
 * Copyright (C) 2016-2020 Nuvoton Technology Corp. All rights reserved.
 ******************************************************************************/
#include "nuc980.h"
#include "uart.h"

#include "IEC60730_CONTROL_PARAM.h"
#include "IEC60730_SAFETY_TEST_LIB.h"


UART_T *g_uart0 = (UART_T *)UART1_BA;

static uint8_t __attribute__((optimize("O0"))) crc8(uint8_t pu8RxBuf[], int16_t length)
{
    uint8_t i, j = 0;
    uint8_t crc = 0;

    while (length--) {
        crc ^= pu8RxBuf[i];
        for (i = 0; i < 8; i++) {
            if (crc & 0x80)
                crc = (crc << 1) ^ 0x07;
            else
                crc <<=1;
        }
    }
    return crc;
}

uint8_t IEC60730_uart_test(void)
{
    int readCount;
    static int err_count = 0;
    int sendCount = 0;
    uint8_t pu8TxBuf[32];
    uint8_t pu8RxBuf[32];

    UART_Open(g_uart0, 115200);

    /* 构建需要进行发送的命令帧  */
    pu8TxBuf[sendCount++] = 0x21;
    pu8TxBuf[sendCount++] = 0x04;
    pu8TxBuf[sendCount++] = 0x09;
    pu8TxBuf[sendCount++] = 0x01;
    pu8TxBuf[sendCount++] = 0x42;
    pu8TxBuf[sendCount++] = 0x00;
    pu8TxBuf[sendCount++] = 0x00;
    pu8TxBuf[sendCount++] = 0x46;
    pu8TxBuf[sendCount++] = 0x00;
    pu8TxBuf[sendCount++] = 0xff;
    pu8TxBuf[sendCount++] = 0x01;
    pu8TxBuf[sendCount++] = 0x31;
    pu8TxBuf[sendCount++] = 0xff;
    pu8TxBuf[sendCount++] = 0x6a;

    UART_Write(g_uart0, pu8TxBuf, sendCount);
    readCount = UART_Read(g_uart0, pu8RxBuf, 14);
    if (readCount == 14) {
        if (crc8(pu8RxBuf, 13) != pu8RxBuf[13]) {
            err_count++;
            if (err_count == 20)
                return TEST_FAIL;
        } else {
            err_count = 0;
            return TEST_PASS;
        }
    } else {
        return TEST_FAIL;
    }
    return TEST_FAIL;
}

/*** (C) COPYRIGHT 2013 Nuvoton Technology Corp. ***/
